package com.jy.api.util;

import org.apache.commons.codec.binary.Base64;


/**
 * @author zeming.fan@swiftpass.cn
 */
public class SignUtil {

    /**
     * 私钥
     */
    private static final String testKey = "h92Tz0wF6QX66hR4pM7VVdXD4NNS3cSO";

    /**
     * @param signType 加密方式
     * @param preStr   加密参数
     * @param key      支付密钥（md5 加密需要）
     * @return
     */
    public static String getSign(String signType, String preStr, String key) {
        if ("RSA_1_256".equals(signType)) {
            try {
                return SignUtil.sign(preStr, "RSA_1_256", /*mchPrivateKey*/testKey);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
        } else {
            return MD5.sign(preStr, "&key=" + key, "utf-8");
        }
        return "";
    }


    public static String sign(String preStr, String signType, String mchPrivateKey) throws Exception {
        RSAUtil.SignatureSuite suite = null;
        if ("RSA_1_1".equals(signType)) {
            suite = RSAUtil.SignatureSuite.SHA1;
        } else if ("RSA_1_256".equals(signType)) {
            suite = RSAUtil.SignatureSuite.SHA256;
        } else {
            throw new Exception("不支持的签名方式");
        }
        byte[] signBuf = RSAUtil.sign(suite, preStr.getBytes("UTF8"),
                mchPrivateKey);
        return new String(Base64.encodeBase64(signBuf), "UTF8");
    }
}
